//
//  UILabel+FixStrikethrough.m
//  FeiFan
//
//  Created by Whirlwind on 2017/3/29.
//  Copyright © 2017年 Wanda Inc. All rights reserved.
//

#import "UILabel+FixStrikethrough.h"
#import "NSObject+runtime.h"

@implementation UILabel (FixStrikethrough)

+ (void)load {
    if ([[[UIDevice currentDevice] systemVersion] hasPrefix:@"10.3"]) {
        [self swizzleOriginInstanceMethod:@selector(drawTextInRect:) swizzledInstanceMethod:@selector(fix_strikethrough_drawTextInRect:) error:nil];
    }
}

- (void)fix_strikethrough_drawTextInRect:(CGRect)rect {
    [self fix_strikethrough_drawTextInRect:rect];
    NSRange range = NSMakeRange(0, self.attributedText.string.length);
    if (range.length == 0) {
        return;
    }
    NSDictionary *dic = [self.attributedText attributesAtIndex:0 effectiveRange:&range];
    if ([dic[NSStrikethroughStyleAttributeName] integerValue] == NSUnderlineStyleSingle) {
        CGSize textSize = [self sizeThatFits:rect.size];
        CGRect textRect = CGRectIntersection(rect, CGRectMake(rect.origin.x, rect.origin.y + (rect.size.height - textSize.height) / 2.f, textSize.width, textSize.height));
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSaveGState(context);
        UIColor *color = dic[NSStrikethroughColorAttributeName] ?: self.textColor;
        CGContextSetFillColor(context, CGColorGetComponents(color.CGColor));
        CGContextFillRect(context, CGRectMake(textRect.origin.x, ceilf(textRect.origin.y + textRect.size.height/2.0f), textRect.size.width, 1));
        CGContextRestoreGState(context);
    }
}

@end
